<template>
  <default-layout>
    <slot name="header" slot="header"></slot>
    <slot name="main" slot="main"></slot>
    <mt-tabbar v-model="selected" class="tabbar" slot="footer">
      <mt-tab-item :id="val.code" v-for="val in menu" :key="val.code">
        <i class="xffont" :class="val.icon" slot="icon"></i>
        {{val.name}}
      </mt-tab-item>
    </mt-tabbar>
    <slot></slot>
  </default-layout>
</template>
<script>
  import {mapGetters} from 'vuex'
  import DefaultLayout from '../default-layout/default-layout'
  export default {
    name: 'tab-bar',
    components: {DefaultLayout},
    computed: {
      ...mapGetters([
        'userInfo',
        'role'
      ]),
      menu: {
        get() {
          if (this.userInfo && this.userInfo.role === 'corp') {
            return [
              {name: '首页', code: 'corpHome', icon: 'xf-shouye1'},
              {name: '资讯', code: 'news', icon: 'xf-zixun'},
              {name: '我的', code: 'corp', icon: 'xf-wode1'}
            ]
          } else {
            return [
              {name: '首页', code: 'home', icon: 'xf-shouye1'},
              {name: '办事大厅', code: 'service', icon: 'xf-banshidating'},
              {name: '资讯', code: 'news', icon: 'xf-zixun'},
              {name: '我的', code: 'user', icon: 'xf-wode1'}
            ]
          }
        }
      }
    },
    data() {
      return {
        selected: ''
      }
    },
    methods: {
      handleSelected($route) {
        let index = this.menu.findIndex(item => item.code === $route.name)
        if (index === -1) return
        setTimeout(() => {
          this.selected = $route.name
        }, 20)
      }
    },
    created() {
      this.handleSelected(this.$route)
      this.$watch('$route', this.handleSelected)
      this.$watch('selected', (newVal) => {
        if (newVal === 'corpLogin' || newVal === 'userLogin') {
          this.$router.push({
            name: newVal,
            query: {
              back: encodeURIComponent(`/${newVal === 'corp' ? 'corp' : 'user'}`)
            }
          })
        } else {
          this.$router.replace({name: newVal})
        }
      })
    }
  }
</script>
<style scoped lang="scss">
  .tabbar{
    position: static;
    border-top: 1px solid #ededed;
    .xffont{
      font-size: .4rem;
    }
  }
</style>
